<!doctype html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="spring," />








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.0" />






<meta name="description" content="为什么需要全局异常处理当我们在开发接口的时候，如果需要对系统的异常进行一个友好的提示时，往往需要捕获各种异常，然后进行异常消息的处理，对不同异常提示不同的错误代码，并给出友好的异常提示信息。这个时候，我们会发现，代码中到处充斥着try-catch用来实现我们的异常友好提示，异常标注多了，自己都会被层出不穷的异常搞萌，最后，异常的提示也不明确了，应用中的代码也更难理解了。这时候，如果我们有一个地方统">
<meta name="keywords" content="spring">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring全局异常处理">
<meta property="og:url" content="https://gitee.com/shuhao/2018/01/19/Spring全局异常处理/index.html">
<meta property="og:site_name" content="Niki">
<meta property="og:description" content="为什么需要全局异常处理当我们在开发接口的时候，如果需要对系统的异常进行一个友好的提示时，往往需要捕获各种异常，然后进行异常消息的处理，对不同异常提示不同的错误代码，并给出友好的异常提示信息。这个时候，我们会发现，代码中到处充斥着try-catch用来实现我们的异常友好提示，异常标注多了，自己都会被层出不穷的异常搞萌，最后，异常的提示也不明确了，应用中的代码也更难理解了。这时候，如果我们有一个地方统">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://gitee.com/blog/images/spring/spring_exception_process_flow.jpg">
<meta property="og:updated_time" content="2018-05-19T03:34:53.410Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Spring全局异常处理">
<meta name="twitter:description" content="为什么需要全局异常处理当我们在开发接口的时候，如果需要对系统的异常进行一个友好的提示时，往往需要捕获各种异常，然后进行异常消息的处理，对不同异常提示不同的错误代码，并给出友好的异常提示信息。这个时候，我们会发现，代码中到处充斥着try-catch用来实现我们的异常友好提示，异常标注多了，自己都会被层出不穷的异常搞萌，最后，异常的提示也不明确了，应用中的代码也更难理解了。这时候，如果我们有一个地方统">
<meta name="twitter:image" content="https://gitee.com/blog/images/spring/spring_exception_process_flow.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/shuhao/2018/01/19/Spring全局异常处理/"/>





  <title> Spring全局异常处理 | Niki </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?cb9f0585e406f878cb2f29c89ad3cdb7";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Niki</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">天道酬勤</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-categories"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/shuhao/blog/2018/01/19/Spring全局异常处理/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Fang ShuHao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/head.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Niki">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Spring全局异常处理
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-01-19T08:45:49+08:00">
                2018-01-19
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/spring/" itemprop="url" rel="index">
                    <span itemprop="name">spring</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="为什么需要全局异常处理"><a href="#为什么需要全局异常处理" class="headerlink" title="为什么需要全局异常处理"></a>为什么需要全局异常处理</h2><p>当我们在开发接口的时候，如果需要对系统的异常进行一个友好的提示时，往往需要捕获各种异常，然后进行异常消息的处理，对不同异常提示不同的错误代码，并给出友好的异常提示信息。这个时候，我们会发现，代码中到处充斥着try-catch用来实现我们的异常友好提示，异常标注多了，自己都会被层出不穷的异常搞萌，最后，异常的提示也不明确了，应用中的代码也更难理解了。<br>这时候，如果我们有一个地方统一处理这些异常，那么可以省去很多地方的try-catch,并且也方便代码的管理和后期的维护（修改了一个异常提示）。恰好，spring就有这个强大的功能。今天我们就来总结下这个功能的实现。</p>
<h2 id="全局异常处理流程"><a href="#全局异常处理流程" class="headerlink" title="全局异常处理流程"></a>全局异常处理流程</h2><img src="/blog/images/spring/spring_exception_process_flow.jpg">
<h2 id="异常处理的结果"><a href="#异常处理的结果" class="headerlink" title="异常处理的结果"></a>异常处理的结果</h2><p> 对于系统抛出的异常，我们可能有如下几个处理预期：</p>
<ol>
<li>统一返回给前台一个错误提示信息：如503页面等。</li>
<li>返回给用户具体异常的处理页面，例如500，我们对于不同的异常，返回给前台的错误页面不同，或者错误页面的提示内容不同。</li>
<li>对于ajax请求，返回给用户错误信息，如json形式错误信息。</li>
</ol>
<h2 id="Spring全局异常处理方式"><a href="#Spring全局异常处理方式" class="headerlink" title="Spring全局异常处理方式"></a>Spring全局异常处理方式</h2><h4 id="使用Spring-MVC提供的SimpleMappingExceptionResolver"><a href="#使用Spring-MVC提供的SimpleMappingExceptionResolver" class="headerlink" title="使用Spring MVC提供的SimpleMappingExceptionResolver"></a>使用Spring MVC提供的SimpleMappingExceptionResolver</h4><p>这种方式具有集成简单，有良好扩展性，对已有代码没有入侵性等优点<br>但是该方法仅能获取异常信息，若出现异常时，对需要获取除异常外的数据情况不适用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.ComponentScan;</span><br><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.servlet.config.annotation.EnableWebMvc;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Properties;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Created by Niki on 2018/1/19 9:27</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebMvc</span></span><br><span class="line"><span class="meta">@ComponentScan</span>(basePackages = &#123;<span class="string">"com.totoro.project.controller"</span>&#125;)</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SimpleMappingExceptionResolverConf</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SimpleMappingExceptionResolver <span class="title">simpleMappingExceptionResolver</span><span class="params">()</span></span>&#123;</span><br><span class="line">        SimpleMappingExceptionResolver simpleMappingExceptionResolver = <span class="keyword">new</span> SimpleMappingExceptionResolver();</span><br><span class="line">        Properties mappings = <span class="keyword">new</span> Properties();</span><br><span class="line"></span><br><span class="line">        simpleMappingExceptionResolver.setDefaultErrorView(<span class="string">"page_505"</span>);</span><br><span class="line">        simpleMappingExceptionResolver.setDefaultStatusCode(<span class="number">505</span>);</span><br><span class="line"></span><br><span class="line">        mappings.put(<span class="string">"org.springframework.web.servlet.PageNotFound"</span>, <span class="string">"page-404"</span>); <span class="comment">//页面没找到异常，统一返回page-404异常页面</span></span><br><span class="line">        mappings.put(<span class="string">"org.springframework.dao.DataAccessException"</span>,<span class="string">"data-access"</span>); <span class="comment">//页面请求参数异常，统一返回data-access异常页面</span></span><br><span class="line">        <span class="comment">//... 对应各种不同的异常，定义不同的处理页面</span></span><br><span class="line"></span><br><span class="line">        simpleMappingExceptionResolver.setExceptionMappings(mappings);</span><br><span class="line">        <span class="keyword">return</span> simpleMappingExceptionResolver;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这个例子是Springboot的实现方式，如果是spring则在Spring配置xml中配置该SimpleMappingExceptionResolver类和对弈异常的映射页面。</p>
<h4 id="实现HandlerExceptionResolver接口自定义异常处理"><a href="#实现HandlerExceptionResolver接口自定义异常处理" class="headerlink" title="实现HandlerExceptionResolver接口自定义异常处理"></a>实现HandlerExceptionResolver接口自定义异常处理</h4><p>我们看下SimpleMappingExceptionResolver类的实现路径<br><figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">SimpleMappingExceptionResolver extends AbstractHandlerExceptionResolver</span><br><span class="line">AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered</span><br></pre></td></tr></table></figure></p>
<p>所以SimpleMappingExceptionResolver也实现了HandlerExceptionResolver，我们来看下HandlerExceptionResolver这个接口<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Interface to be implemented by objects that can resolve exceptions thrown during</span></span><br><span class="line"><span class="comment"> * handler mapping or execution, in the typical case to error views. Implementors are</span></span><br><span class="line"><span class="comment"> * typically registered as beans in the application context.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Error views are analogous to JSP error pages but can be used with any kind of</span></span><br><span class="line"><span class="comment"> * exception including any checked exception, with potentially fine-grained mappings for</span></span><br><span class="line"><span class="comment"> * specific handlers.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Juergen Hoeller</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 22.11.2003</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">HandlerExceptionResolver</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Try to resolve the given exception that got thrown during handler execution,</span></span><br><span class="line"><span class="comment">	 * returning a &#123;<span class="doctag">@link</span> ModelAndView&#125; that represents a specific error page if appropriate.</span></span><br><span class="line"><span class="comment">	 * &lt;p&gt;The returned &#123;<span class="doctag">@code</span> ModelAndView&#125; may be &#123;<span class="doctag">@linkplain</span> ModelAndView#isEmpty() empty&#125;</span></span><br><span class="line"><span class="comment">	 * to indicate that the exception has been resolved successfully but that no view</span></span><br><span class="line"><span class="comment">	 * should be rendered, for instance by setting a status code.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> request current HTTP request</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> response current HTTP response</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> handler the executed handler, or &#123;<span class="doctag">@code</span> null&#125; if none chosen at the</span></span><br><span class="line"><span class="comment">	 * time of the exception (for example, if multipart resolution failed)</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@param</span> ex the exception that got thrown during handler execution</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@return</span> a corresponding &#123;<span class="doctag">@code</span> ModelAndView&#125; to forward to, or &#123;<span class="doctag">@code</span> null&#125;</span></span><br><span class="line"><span class="comment">	 * for default processing</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="function">ModelAndView <span class="title">resolveException</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span></span>;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>从注释可以大致得出，这个接口定义了系统中，异常与错误页面的映射。所以自定义的HandlerExceptionResolver和使用SimpleMappingExceptionResolver处理全局异常的使用是一样的。</p>
<h4 id="使用-ExceptionHandler注解实现异常处理"><a href="#使用-ExceptionHandler注解实现异常处理" class="headerlink" title="使用@ExceptionHandler注解实现异常处理"></a>使用@ExceptionHandler注解实现异常处理</h4><p>通过Spring提供的@ExceptionHandler我们可以对某个特定的异常进行特殊处理。结合@ControllerAdvice注解，我们可以实现对系统所有的Controller进行监控，并统一处理其中的异常，我们来看这种处理异常方式的代码。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.totoro.common.Result;</span><br><span class="line"><span class="keyword">import</span> org.springframework.http.HttpStatus;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.ControllerAdvice;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.ExceptionHandler;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.ResponseBody;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.bind.annotation.ResponseStatus;</span><br><span class="line"><span class="keyword">import</span> org.springframework.web.servlet.ModelAndView;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletRequest;</span><br><span class="line"><span class="keyword">import</span> javax.servlet.http.HttpServletResponse;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by Niki on 2018/1/19 9:34</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@ControllerAdvice</span> <span class="comment">//处理所有的Controller的异常</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GlobalExceptionHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//返回异常页面，并且添加异常数据</span></span><br><span class="line">    <span class="meta">@ExceptionHandler</span>(Exception.class)</span><br><span class="line">    <span class="meta">@ResponseStatus</span>(HttpStatus.NOT_FOUND)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> ModelAndView <span class="title">handle404Error</span><span class="params">(HttpServletRequest request, HttpServletResponse response, Exception e)</span></span>&#123;</span><br><span class="line">        ModelAndView mav = <span class="keyword">new</span> ModelAndView();</span><br><span class="line">        mav.addObject(<span class="string">"message"</span>, <span class="string">"访问页面异常！"</span>);</span><br><span class="line">        mav.setViewName(<span class="string">"404"</span>);</span><br><span class="line">        <span class="keyword">return</span> mav;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//返回ajax异常</span></span><br><span class="line">    <span class="meta">@ExceptionHandler</span>(AjaxException.class)</span><br><span class="line">    <span class="meta">@ResponseBody</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result&lt;String&gt; <span class="title">ajaxException</span><span class="params">(HttpServletRequest request, HttpServletResponse response)</span></span>&#123;</span><br><span class="line">        Result&lt;String&gt; result = <span class="keyword">new</span> Result&lt;String&gt;();</span><br><span class="line">        result.setMsgCode(<span class="string">"500"</span>);</span><br><span class="line">        result.setMsg(<span class="string">"访问接口"</span>+request.getRequestURL().toString()+<span class="string">"异常"</span>);</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>可以看出这种方式可以处理错误页面，和Ajax方式请求，并返回json格式错误信息。这种方式同样对代码没有入侵，并且可以很轻松的获取到请求方法的各种请求参数。</p>
<h4 id="自定义切面进行异常捕获处理"><a href="#自定义切面进行异常捕获处理" class="headerlink" title="自定义切面进行异常捕获处理"></a>自定义切面进行异常捕获处理</h4><p>上面一种方法，使用@ControllerAdvice来处理全局异常，会捕获扫描包下面所有的Controller，如果需要更精确的细分，只需要处理某个Controller，或者某个RequestMapping时，如何做呢？我们通过自己实现切面的方式，通过aop来实现自定义的异常拦截处理。我们看代码</p>
<p>定义切面的注释<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.annotation.ElementType ;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 处理controller抛出的异常，减少工程中代码量</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> shuhao_fang <span class="doctag">@date</span> 2018年1月16日 下午7:21:28</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Target</span>(ElementType.METHOD)</span><br><span class="line"><span class="meta">@Retention</span>(RetentionPolicy.RUNTIME)</span><br><span class="line"><span class="keyword">public</span> <span class="meta">@interface</span> ResultExceptionHandler &#123;</span><br><span class="line">    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>处理注释的切面拦截器<br><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.aspectj.lang.ProceedingJoinPoint ;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.Around ;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.Aspect ;</span><br><span class="line"><span class="keyword">import</span> org.aspectj.lang.annotation.Pointcut ;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.Logger ;</span><br><span class="line"><span class="keyword">import</span> org.slf4j.LoggerFactory ;</span><br><span class="line"><span class="keyword">import</span> org.springframework.stereotype.Component ;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> com.kingdee.common.error.ErrorCode ;</span><br><span class="line"><span class="keyword">import</span> com.kingdee.common.exception.ResultException ;</span><br><span class="line"><span class="keyword">import</span> com.kingdee.common.util.ResultUtil ;</span><br><span class="line"><span class="keyword">import</span> com.kingdee.open.datain.model.Result ;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 用来处理单个方法需要处理异常的情况</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> shuhao_fang <span class="doctag">@date</span> 2018年1月16日 下午7:24:32</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Aspect</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ResultExceptionAspect</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Logger logger = LoggerFactory.getLogger(ResultExceptionAspect.class);</span><br><span class="line">    <span class="meta">@Pointcut</span>(<span class="string">"@annotation(com.kingdee.common.aop.ResultExceptionHandler)"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pointcut</span><span class="params">()</span></span>&#123;&#125;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Around</span>(<span class="string">"pointcut()"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Object <span class="title">dealException</span><span class="params">(ProceedingJoinPoint joinPoint)</span></span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Object[] args = joinPoint.getArgs();</span><br><span class="line">            <span class="keyword">return</span> joinPoint.proceed(args);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (ResultException e) &#123;</span><br><span class="line">            <span class="keyword">return</span> ResultUtil.error(e.getErrorMsg(), e.getErrorCode(), e.getData());</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">            logger.error(<span class="string">"ResultExceptionAspect has error!"</span>,e);</span><br><span class="line">            <span class="keyword">return</span> ResultUtil.error(ErrorCode.E_500.getMsg(), ErrorCode.E_500.getCode());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>从这个类中，我们可以看出通过@ResultExceptionHandler注释过的方法，如果抛出了异常会在ResultExceptionAspect中进行处理。这里只针对ResultException这个自定义的异常进行特殊处理，以及任何其他的异常，都会抛出500错误。所以在被@ResultExceptionHandler注释的方法中，我们无需通过try-catch来处理未受检查的异常，全部交给这个aop切面进行处理。</p>
<p>优先级</p>
<p>既然在SpringMVC中有两种处理异常的方式，那么就存在一个优先级的问题：</p>
<p>当发生异常的时候，SpringMVC会如下处理：</p>
<p>（1）SpringMVC会先从配置文件找异常解析器HandlerExceptionResolver</p>
<p>（2）如果找到了异常异常解析器，那么接下来就会判断该异常解析器能否处理当前发生的异常</p>
<p>（3）如果可以处理的话，那么就进行处理，然后给前台返回对应的异常视图</p>
<p>（4）如果没有找到对应的异常解析器或者是找到的异常解析器不能处理当前的异常的时候，就看当前的Controller中有没有提供对应的异常处理器，如果提供了就由Controller自己进行处理并返回对应的视图</p>
<p>（5）如果配置文件里面没有定义对应的异常解析器，而当前Controller中也没有定义的话，那么该异常就会被抛出来。</p>
<h2 id="扩展"><a href="#扩展" class="headerlink" title="扩展"></a>扩展</h2><p>为什么新加入的HandlerExceptionResolver为什么会执行，因为我们看源码也看到，只要返回ModelAndView就不执行了，那是因为，是根据HandlerExceptionResolver中的order属性排序的，而默认的HandlerExceptionResolver都继承自AbstractHandlerExceptionResolver，而它的order属性值是最大的int值，所以，默认添加的会是最先执行的。<br>public abstract class AbstractHandlerExceptionResolver implements HandlerExceptionResolver, Ordered {<br>private int order = Ordered.LOWEST_PRECEDENCE;<br>}<br>public interface Ordered {<br>int HIGHEST_PRECEDENCE = -2147483648;<br>int LOWEST_PRECEDENCE = 2147483647;</p>
<p>int getOrder();<br>}</p>
<blockquote>
<blockquote>
<p>参考<br><a href="http://blog.csdn.net/initphp/article/details/39028155" target="_blank" rel="external">Spring 异常处理HandlerExceptionResolver</a><br><a href="http://www.cnblogs.com/lcngu/p/7096529.html" target="_blank" rel="external">Spring全局异常处理的三种方式</a><br>[SpringMVC异常处理机制详解]<a href="http://www.cnblogs.com/fangjian0423/p/springMVC-exception-analysis.html" target="_blank" rel="external">http://www.cnblogs.com/fangjian0423/p/springMVC-exception-analysis.html</a>)</p>
</blockquote>
</blockquote>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/spring/" rel="tag"># spring</a>
          
        </div>
      

      
        
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/01/18/Java-BitSet实现/" rel="next" title="Java BitSet实现">
                <i class="fa fa-chevron-left"></i> Java BitSet实现
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/01/19/java中字符创拼接方法对比/" rel="prev" title="java中字符创拼接方法对比">
                java中字符创拼接方法对比 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNjY5NS8xMzIzMA=="></div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/blog/images/head.jpg"
               alt="Fang ShuHao" />
          <p class="site-author-name" itemprop="name">Fang ShuHao</p>
           
              <p class="site-description motion-element" itemprop="description"></p>
          
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">135</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories">
                <span class="site-state-item-count">35</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags">
                <span class="site-state-item-count">93</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#为什么需要全局异常处理"><span class="nav-number">1.</span> <span class="nav-text">为什么需要全局异常处理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全局异常处理流程"><span class="nav-number">2.</span> <span class="nav-text">全局异常处理流程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异常处理的结果"><span class="nav-number">3.</span> <span class="nav-text">异常处理的结果</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Spring全局异常处理方式"><span class="nav-number">4.</span> <span class="nav-text">Spring全局异常处理方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#使用Spring-MVC提供的SimpleMappingExceptionResolver"><span class="nav-number">4.0.1.</span> <span class="nav-text">使用Spring MVC提供的SimpleMappingExceptionResolver</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#实现HandlerExceptionResolver接口自定义异常处理"><span class="nav-number">4.0.2.</span> <span class="nav-text">实现HandlerExceptionResolver接口自定义异常处理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#使用-ExceptionHandler注解实现异常处理"><span class="nav-number">4.0.3.</span> <span class="nav-text">使用@ExceptionHandler注解实现异常处理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#自定义切面进行异常捕获处理"><span class="nav-number">4.0.4.</span> <span class="nav-text">自定义切面进行异常捕获处理</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展"><span class="nav-number">5.</span> <span class="nav-text">扩展</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fang ShuHao</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    
    
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.0"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	





  





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  



  
  

  

  

  

  


  

</body>
</html>
